package com.qianfeng.controller.user;


import com.qianfeng.bean.user.UserBean;
import com.qianfeng.message.Message;
import com.qianfeng.message.ResponseMessage;
import com.qianfeng.service.user.UserService;
import com.qianfeng.utils.LogUtil;
import com.qianfeng.utils.MD5;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/user/")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;






    @RequestMapping("toLogin")
    public ModelAndView toLogin(ModelAndView modelAndView) {
        logger.info("进入方法......");

        modelAndView.setViewName("user/login");

        logger.info("开始跳转页面 : user/login");

        return modelAndView;
    }

    @RequestMapping("login")
    @ResponseBody
    public ResponseMessage login(UserBean userBean) {

        logger.info("进入方法, 参数是"+userBean);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userBean.getUserName(),userBean.getPassword());

        ResponseMessage message ;
        try {

            subject.login(token);

            message = new ResponseMessage(Message.REQUEST_SUCCESS.getCode(), Message.REQUEST_SUCCESS.getMessage());

            logger.info("执行完毕, 返回值是"+message);

        } catch (Exception e) {
            LogUtil.logErr(logger, e);
            message = new ResponseMessage(Message.REQUEST_FAIL.getCode(), Message.REQUEST_FAIL.getMessage());
        }

        return message;
    }

    @RequestMapping("logout")
    @ResponseBody
    public ResponseMessage logout() {

        logger.info("进入方法, 参数是");
        Subject subject = SecurityUtils.getSubject();

        ResponseMessage message ;
        try {
            subject.logout();
            message = new ResponseMessage(Message.REQUEST_SUCCESS.getCode(), Message.REQUEST_SUCCESS.getMessage());
            logger.info("执行完毕, 返回值是"+message);

        } catch (Exception e) {
            LogUtil.logErr(logger, e);
            message = new ResponseMessage(Message.REQUEST_FAIL.getCode(), Message.REQUEST_FAIL.getMessage());
        }
        return message;
    }

}
